// pages/my/team/index.js
const api = require('../../../fetch/api')
const app = getApp()
const {
  baseURL
} = require('../../../fetch/http')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseURL: baseURL,
    tabs: [ '一级团队', '二级团队' ,'三级团队'],
    tabIndex: 0,
    arr: [],
    loading: false,
    finished: false,
    page: 1,
    limit: 10,
  },
  async team() {
    if (!this.data.loading) {
      this.setData({
        loading: true
      })
      let res = await api.team({
        page: this.data.page,
        type: this.data.tabIndex,
        limit: this.data.limit
      })
      let finished = false
      // 结果长度为不足一页说明加载完毕
      res.data.length < this.data.limit && (finished = true)
      this.setData({
        arr: [...this.data.arr, ...res.data],
        finished,
        loading: false
      })
    }
  },
  clear() {
    this.setData({
      arr: [],
      page: 1,
      loading: false,
      finished: false
    })
  },
  switchTab(e) {
    const {
      index
    } = app.dataSet(e)
    if (this.data.tabIndex != index) {
      this.setData({
        tabIndex: index,
      })
      this.clear()
      this.team()
    }
  },
  userinfo() {
    // let res = await api.userinfo()
    let res = {
      data: app.globalData.userinfo
    }
    this.setData({
      id: res.data.id,
      total: res.data.team, // 团队
      role: res.data.role, // 2 合伙人 1 普通
      popularize: res.data.popularize // 推广
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.team()
    this.userinfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log("到底了");
    let {
      finished,
      page
    } = this.data
    if (!finished) {
      this.setData({
        page: ++page
      })
      this.team();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (!wx.getStorageSync('token')) {
      app.toast('请登录')
      return false
    }

    if (res.from === 'button') {
      let userId = wx.getStorageSync('id')
      return {
        title: '天喜鑫宝',
        imageUrl: this.data.baseURL + '/img/share_img_2.png',
        path: `/pages/home/goodsDetail/index?userId=${userId}&id=${this.data.id}`
      }
    }
    let userId = wx.getStorageSync('id')
    return {
      title: '天喜鑫宝',
      imageUrl: this.data.baseURL + '/img/share_img_2.png',
      path: `/pages/home/goodsDetail/index?userId=${userId}&id=${this.data.id}`
    }
  }
})